#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const SRC_ROOT = path.resolve(__dirname, 'src'); // 项目 src 目录
const FILE_EXTS = ['.vue', '.js', '.ts'];

// 获取 src 下的所有文件
function getAllFiles(dir) {
    let results = [];
    fs.readdirSync(dir, { withFileTypes: true }).forEach(entry => {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
            results = results.concat(getAllFiles(fullPath));
        } else if (FILE_EXTS.includes(path.extname(entry.name))) {
            results.push(fullPath);
        }
    });
    return results;
}

// 查找 src 下对应路径的实际文件（忽略大小写）
function findActualFile(relativePath) {
    const parts = relativePath.split('/');
    let current = SRC_ROOT;

    for (let i = 0; i < parts.length; i++) {
        if (!fs.existsSync(current)) return null;
        const entries = fs.readdirSync(current);
        const match = entries.find(e => e.toLowerCase() === parts[i].toLowerCase());
        if (!match) return null;
        current = path.join(current, match);
    }

    // 如果是目录，尝试加上扩展名
    if (!fs.existsSync(current)) {
        for (const ext of FILE_EXTS) {
            if (fs.existsSync(current + ext)) return current + ext;
        }
        return null;
    }
    return current;
}

// 检查 import 路径是否存在
function checkImports(filePath) {
    const content = fs.readFileSync(filePath, 'utf-8');
    const importRegex = /import\s+.*\s+from\s+['"](.*)['"]/g;
    let match;
    while ((match = importRegex.exec(content)) !== null) {
        let importPath = match[1];
        if (!importPath.startsWith('@/')) continue;

        const relativePath = importPath.replace(/^@\//, '');
        const actualFile = findActualFile(relativePath);

        if (!actualFile) {
            console.log(`❌ ${filePath} -> ${importPath} (文件不存在或路径大小写错误)`);

            // 自动生成修正路径
            const candidates = fs.readdirSync(SRC_ROOT, { withFileTypes: true });
            console.log(`   建议检查 /src/${relativePath}`);
        }
    }
}

const allFiles = getAllFiles(SRC_ROOT);
allFiles.forEach(checkImports);

console.log('扫描完成。');

